package ICM.server;

import java.sql.*;

import common.*;

public class UserManager {
	
	
	public static User Login(int ID, String password)
	{
		User user = null;
		DBManager db = DBManager.getInstance();
		try {
			PreparedStatement stmt = db.getConnection().prepareStatement("SELECT * FROM users WHERE ID=? AND Password=?;");
			stmt.setInt(1, ID);
			stmt.setString(2, password);
			ResultSet rs = stmt.executeQuery();
			if(rs.next())
			{
				user=new User();
				user.setDepartment(rs.getString(7));
				user.setId(ID);
				user.setPassword(password);
				user.setRole(rs.getString(5));
				user.setFirstname(rs.getString(2));
				user.setLastname(rs.getString(3));
				user.setEmail(rs.getString(6));
			}
			rs.close();
		} catch (SQLException e) {
			e.printStackTrace();	
		}
		return user;
	}
	
	public static int AddUser(int ID, String FirstName, String LastName, String Password, String Role, String Email){
		DBManager db = DBManager.getInstance();
		try {
			PreparedStatement stmt1 = db.getConnection().prepareStatement("SELECT ID FROM users WHERE ID=?;");
			stmt1.setInt(1, ID);
			ResultSet rs1 = stmt1.executeQuery();
			
			if(rs1.next()!=false){
				rs1.close();
				return -1;
			}
			else{
				rs1.close();
				PreparedStatement stmt2 = db.getConnection().prepareStatement("INSERT INTO users (ID,FirstName,LastName,Password,Role,Email) VALUES (?,?,?,?,?,?);");
				stmt2.setInt(1, ID);
				stmt2.setString(2, FirstName);
				stmt2.setString(3,LastName);
				stmt2.setString(4, Password);
				stmt2.setString(5, Role);
				stmt2.setString(6, Email);
				
		
			    stmt2.executeUpdate();
				return 1;
			}	
		} catch (SQLException e) {
			e.printStackTrace();
			return -2;
		}
	}

}
